﻿namespace YidanSoft.Library.EditorUtility.WinControls
{
    using System;
    using System.Drawing;

    public class DoubleBuffer
    {
        private Graphics buffer;
        private int bufferHeight;
        private int bufferWidth;
        private Bitmap surface;

        private void Cleanup()
        {
            if (this.buffer != null)
            {
                this.buffer.Dispose();
                this.buffer = null;
            }
            if (this.surface != null)
            {
                this.surface.Dispose();
                this.surface = null;
            }
        }

        public void Dispose()
        {
            this.Cleanup();
        }

        public void PaintBuffer(Graphics dest, int x, int y)
        {
            dest.DrawImage(this.surface, x, y);
        }

        public Graphics RequestBuffer(int width, int height)
        {
            if (((width != this.bufferWidth) || (height != this.bufferHeight)) || (this.buffer == null))
            {
                this.Cleanup();
                this.surface = new Bitmap(width, height);
                this.buffer = Graphics.FromImage(this.surface);
                this.bufferWidth = width;
                this.bufferHeight = height;
            }
            return this.buffer;
        }
    }
}

